package com.brayan.webapp.repository.usermgmt;

import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;

import com.brayan.webapp.model.realestate.Tenant;

/**
 * A tenant data repository that offers several methods.
 * 
 * @author Brayan Zimmerli
 * 
 */
@Stateless
public class TenantRepository {

	@Inject
	transient private Logger LOGGER;

	@PersistenceContext
	private EntityManager em;

	public Tenant findById(Long id) {
		return em.find(Tenant.class, id);
	}

	public Tenant saveTenant(Tenant tenant) {
		Tenant savedTenant = tenant;
		if (em.contains(tenant)) {
			savedTenant = em.merge(tenant);
			LOGGER.info("Saved existing tenant " + tenant.getGivenname() + " " + tenant.getSurname());
		} else {
			// Because Roles already exist, use merge also in this case where no tenant exists.
			savedTenant = em.merge(tenant);
			LOGGER.info("Saved new tenant " + tenant.getGivenname() + " " + tenant.getSurname());
		}

		return savedTenant;
	}

	public Tenant findByEmail(String email) {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Tenant> criteria = cb.createQuery(Tenant.class);
		Root<Tenant> tenant = criteria.from(Tenant.class);
		// Swap criteria statements if you would like to try out type-safe
		// criteria queries, a new
		// feature in JPA 2.0
		// criteria.select(User).where(cb.equal(User.get(User_.name), email));
		criteria.select(tenant).where(cb.equal(tenant.get("email"), email));
		Tenant existingTenant = null;
		try {
			existingTenant = em.createQuery(criteria).getSingleResult();
		} catch (NoResultException noEx) {
			return null;
		}
		return existingTenant;
	}

	public List<Tenant> findAllOrderedByName() {
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Tenant> criteria = cb.createQuery(Tenant.class);
		Root<Tenant> tenant = criteria.from(Tenant.class);
		// Swap criteria statements if you would like to try out type-safe
		// criteria queries, a new
		// feature in JPA 2.0
		// criteria.select(User).orderBy(cb.asc(User.get(User_.name)));
		criteria.select(tenant).orderBy(cb.asc(tenant.get("name")));
		return em.createQuery(criteria).getResultList();
	}
}
